package com.shareyi.jshop.autocode.tableutil;

import com.shareyi.jshop.autocode.domain.Column;
import com.shareyi.jshop.autocode.domain.RequireConfig;
import com.shareyi.jshop.autocode.domain.RequireInfo;
import com.shareyi.jshop.autocode.domain.TableModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by david on 2016/4/24.
 */
public class RequireUtil {


    public Map<String,RequireConfig> requireConfigMap;


    /**
     * 获取requireJs的依赖信息
     * @param tableModel
     * @param listName
     * @return
     */
    public RequireInfo getRequireInfo(TableModel tableModel,String listName){

        RequireInfo requireInfo=new RequireInfo();
        List<Column> columnList=tableModel.getTableDefine().getColumns();
        List<String> columnNameList=tableModel.getColumNameList(listName);

        if(CollectionUtils.isEmpty(columnList)||CollectionUtils.isEmpty(columnNameList) || MapUtils.isEmpty(requireConfigMap)){
            return requireInfo;
        }

        for(Column column:columnList){
            if(columnNameList.contains(column.getColumnName())){
                checkColumnNeedRequre(requireInfo,column);
            }
        }

        requireInfo.sortModule();
        return requireInfo;

    }




    /**
     * 获取requireJs的依赖信息
     * @param tableModel
     * @param columns
     * @return
     */
    public RequireInfo getRequireInfoByColumns(TableModel tableModel,String columns){

        RequireInfo requireInfo=new RequireInfo();
        List<Column> columnList=tableModel.getTableDefine().getColumns();
        List<String> columnNameList= AutoCodeStringUtils.strToList(columns, ",");

        if(CollectionUtils.isEmpty(columnList)||CollectionUtils.isEmpty(columnNameList) || MapUtils.isEmpty(requireConfigMap)){
            return requireInfo;
        }

        for(Column column:columnList){
            if(columnNameList.contains(column.getColumnName())){
                checkColumnNeedRequre(requireInfo,column);
            }
        }
        requireInfo.sortModule();
        return requireInfo;

    }

    private void checkColumnNeedRequre(RequireInfo requireInfo, Column column) {

        RequireConfig requireConfig=requireConfigMap.get(column.getJspTag());
        if(requireConfig==null){
            requireConfig=requireConfigMap.get(column.getJspTag().toUpperCase());
        }
        if(requireConfig==null){
            requireConfig=requireConfigMap.get(column.getJspTag().toLowerCase());
        }


        if(requireConfig!=null){
            requireInfo.addColumnToModule(column,requireConfig);
        }
    }


    public Map<String, RequireConfig> getRequireConfigMap() {
        return requireConfigMap;
    }

    public void setRequireConfigMap(Map<String, RequireConfig> requireConfigMap) {
        this.requireConfigMap = requireConfigMap;
    }
}
